package com.fenghongzhang.day016;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ListView lv;

    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        lv = (ListView) findViewById(R.id.lv);

        //2,数据源 -> 异步下载
        new MyTask().execute("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1");

        //适配器

    }

    class MyTask extends AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... strings) {
            URL url = null;
            try {
                url = new URL(strings[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                Log.i(TAG, "doInBackground: ");
                if (connection.getResponseCode() == 200) {
                    Log.i(TAG, "doInBackground: ");
                    InputStream inputStream = connection.getInputStream();
                    StringBuffer buffer = new StringBuffer();
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = inputStream.read(bytes)) != -1) {
                        buffer.append(new String(bytes, 0, len));
                    }
                    Log.i(TAG, "doInBackground: "+buffer.toString());
                    return buffer.toString();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
//            //Gson
//            Gson gson = new Gson();
//            Food food = gson.fromJson(s, Food.class);
//            //給數據源複製
//            //把每次查询都有加入到数据源中.
//
//            List<Food.DataBean> data = food.getData();
//            list.addAll(data);
//
//            //移除尾布局
//            lv.removeFooterView(inflate);
//
//            myAdapter.notifyDataSetChanged();

            Food food = JSON.parseObject(s, Food.class);
            List<Food.DataBean> data = food.getData();
            Log.i(TAG, "onPostExecute: "+data.size());
            MyAdapter myAdapter = new MyAdapter(data, MainActivity.this);
            lv.setAdapter(myAdapter);


        }
    }

}
